package com.ecoolex.discount.sales.ws;

import java.time.Instant;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.ecoolex.discount.sales.core.external.v2.YWExternalService;
import com.ecoolex.discount.sales.core.external.v2.pojo.GetStoresResponse;
import com.ecoolex.discount.sales.core.manager.YWStoreCateManager;
import com.ecoolex.discount.sales.core.manager.YWStoreManager;
import com.ecoolex.discount.sales.entity.YWStore;
import com.ecoolex.discount.sales.entity.YWStoreCate;
import com.ecoolex.discount.sales.pojo.GetStoriesDTO;

@Service
public class YWStoriesServiceImpl implements YWStoreService {
	@Autowired
	YWStoreManager ywStoreManager;

	@Autowired
	YWStoreCateManager ywStoreCateManager;

	@Autowired
	YWExternalService ywExternalService;

	@Override
	public List<GetStoriesDTO> getAllStories(String channelId) {
		String token = ywExternalService.getToken(channelId);
		GetStoresResponse resp = ywExternalService.getStores(token);
		List<GetStoriesDTO> getStoriesDTOS = Collections.EMPTY_LIST;
		if (Objects.nonNull(resp) && YWExternalService.SUCCESS.equals(resp.getErrno())) {
			List<GetStoresResponse.Store> stores = resp.getData();
			if (CollectionUtils.isNotEmpty(stores)) {
				getStoriesDTOS = stores.stream().map(store -> {
					GetStoriesDTO storiesDTO = new GetStoriesDTO();
					BeanUtils.copyProperties(store, storiesDTO);
					if (Objects.nonNull(store.getUpdateTime()) && store.getUpdateTime() > 0) {
						storiesDTO.setUpdateTime(Date.from(Instant.ofEpochSecond(store.getUpdateTime())));
					}
					return storiesDTO;
				}).collect(Collectors.toList());
			}

		}
		return getStoriesDTOS;
	}

	@Override
	public List<GetStoriesDTO> getAllStoriesFromDB(String channelId) {
		List<YWStore> stories = ywStoreManager.getAllStories(channelId);
		List<GetStoriesDTO> getStoriesDTOS = Collections.EMPTY_LIST;
		if (!CollectionUtils.isEmpty(stories)) {
			getStoriesDTOS = stories.stream().map(store -> {
				GetStoriesDTO storiesDTO = new GetStoriesDTO();
				BeanUtils.copyProperties(store, storiesDTO);
				storiesDTO.setUpdateTime(store.getLastModifiedTime());
				List<YWStoreCate> cates = ywStoreCateManager.getCateByStoreId(store.getStoreId());
				if (!CollectionUtils.isEmpty(cates)) {
					List<String> _cates = cates.stream().map(YWStoreCate::getCategroy).collect(Collectors.toList());
					storiesDTO.setCategories(_cates);
					storiesDTO.setBizCategory(_cates.stream().collect(Collectors.joining(",")));
				}
				return storiesDTO;
			}).collect(Collectors.toList());
		}
		return getStoriesDTOS;
	}

}
